package com.lazyframework.commons.support.mp;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Create by lazy in 2019/10/8
 */
public class DbEnumTypeHandler<E extends DbEnum> extends BaseTypeHandler<E> {

    private E[] enums;

    private Class<E> enumType;

    public DbEnumTypeHandler() {}

    public DbEnumTypeHandler(Class<E> enumType) {
        this.enumType = enumType;
        this.enums = enumType.getEnumConstants();
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.value());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return handler(rs.getInt(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return handler(rs.getInt(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return handler(cs.getInt(columnIndex));
    }

    private E handler(int value) {
        for (E anEnum : enums) {
            if (value == anEnum.value()) {
                return anEnum;
            }
        }
        return null;
    }
}
